import json
import time

import jwt
import numpy as np
from django import http
from django.core.mail.backends import console
from django.http import HttpResponse
from django.shortcuts import render
from django.conf import settings

# Create your views here.
from django.views import View
from rest_framework.views import APIView


from rest_framework.response import Response

from .models import LunZhuan, ShopChannel,ShopCategory,Shop,Active
from django.core.paginator import Paginator, EmptyPage



from django.conf import settings
from django.core.files.storage import Storage
from django.utils.deconstruct import deconstructible
from fdfs_client.client import Fdfs_client, get_tracker_conf




# 找到轮转的数据
class BannerView(APIView):
    def get(self,request,*args,**kwargs):



        """新闻列表展示功能"""
        try:
            # 获取NewsChannel对象
            bannerList = LunZhuan.objects.all()

        except LunZhuan.DoseNotExist:
            return http.HttpResponseNotFound('未找到轮转区的数据')

        data = []
        for instance in bannerList:

            data.append({
                'createTime':instance.create_time,
                'id':instance.id,
                'imageUrl':instance.imageUrl.__str__(),
                'isDeleted':instance.isDeleted,
                'linkUrl':instance.linkUrl.__str__(),
                'sort':instance.sort,
                'title':instance.title,
                'updateTime':instance.update_time
            })


        return Response({"data":data,"code":200})

# 商品导航数据
class CategoryView(APIView):
    def get(self,request,*args,**kwargs):



        """新闻列表展示功能"""
        try:
            # 获取NewsChannel对象
            categoryList = ShopChannel.objects.all()
        except:
            return http.HttpResponseNotFound('未找到轮转区的数据')
        data = []

        for instance in categoryList:
            data.append({
                'id': instance.id,
                'imageUrl': instance.imageUrl.__str__(),
                'name': instance.name,
            })

        return Response({"data": data, "code": 200})






#活动渲染区域Active
class ActiveView(APIView):
    def get(self,request,*args,**kwargs):



        """新闻列表展示功能"""
        try:
            # 获取NewsChannel对象
            activeList = Active.objects.all()

        except Active.DoseNotExist:
            return http.HttpResponseNotFound('未找到轮转区的数据')

        data = []
        for instance in activeList:

            data.append({
                'category2Id':instance.category2Id_id,
                'id':instance.id,
                'imageUrl':instance.imageUrl.__str__(),
            })


        return Response({"data":data,"code":200})



#人气推荐
class HotView(APIView):
    def get(self,request,*args,**kwargs):



        """新闻列表展示功能"""
        try:
            # 获取NewsChannel对象
            hoteList = Shop.objects.order_by('-saleCount')

        except:
            return http.HttpResponseNotFound('未找到轮转区的数据')

        data = []
        for instance in hoteList:

            data.append({
                'applyUser':instance.applyUser,
                'category1Id':instance.category1Id_id,
                'category2Id':instance.category2Id_id,
                'createTime': instance.create_time,
                'detailList': instance.detailList,
                'floralLanguage': instance.floralLanguage,
                'id': instance.id,
                'imageUrl': instance.imageUrl.__str__(),
                'isDeleted': instance.isDeleted,
                'isRecommend': instance.isRecommend,
                'marketPrice': instance.marketPrice,
                'material': instance.material,
                'name': instance.name,
                'packing': instance.packing,
                'price': instance.price,
                'saleCount': instance.saleCount,
                'stockCount': instance.stockCount,
                'updateTime': instance.update_time,
            })


        return Response({"data":data,"code":200})



#猜你喜欢
class GuessView(APIView):
    def get(self,request,*args,**kwargs):



        """新闻列表展示功能"""
        try:
            # 获取NewsChannel对象
            guessList = Shop.objects.order_by('category1Id_id')

        except:
            return http.HttpResponseNotFound('未找到轮转区的数据')

        data = []
        for instance in guessList:

            data.append({
                'applyUser':instance.applyUser,
                'category1Id':instance.category1Id_id,
                'category2Id':instance.category2Id_id,
                'createTime': instance.create_time,
                'detailList': instance.detailList,
                'floralLanguage': instance.floralLanguage,
                'id': instance.id,
                'imageUrl': instance.imageUrl.__str__(),
                'isDeleted': instance.isDeleted,
                'isRecommend': instance.isRecommend,
                'marketPrice': instance.marketPrice,
                'material': instance.material,
                'name': instance.name,
                'packing': instance.packing,
                'price': instance.price,
                'saleCount': instance.saleCount,
                'stockCount': instance.stockCount,
                'updateTime': instance.update_time,
            })


        return Response({"data":data,"code":200})


class GoodCategoryView(APIView):
    def get(self,request,*args,**kwargs):
        # 接收参数 '{"k":"v"}'  ---> {"k":"v"}

        # page = request.GET.get('page', '').strip()
        # limit = request.GET.get('limit', '').strip()
        # int(limit)

        category1Id_id = request.GET.get('category1Id', '').strip()
        category2Id_id = request.GET.get('category2Id', '').strip()



        if category1Id_id != '':

            # print(category1Id_id)
            Lists = Shop.objects.filter(category1Id_id=category1Id_id).all()
            total = Shop.objects.filter(category1Id_id=category1Id_id).count()


        if category2Id_id != '':
            print(category2Id_id)
            Lists = Shop.objects.filter(category2Id_id=category2Id_id).all()
            total = Shop.objects.filter(category2Id_id=category2Id_id).count()

        data = []
        for instance in Lists:

            data.append({
                'applyUser': instance.applyUser,
                'category1Id': instance.category1Id_id,
                'category2Id': instance.category2Id_id,
                'createTime': instance.create_time,
                'detailList': instance.detailList,
                'floralLanguage': instance.floralLanguage,
                'id': instance.id,
                'imageUrl': instance.imageUrl.__str__(),
                'isDeleted': instance.isDeleted,
                'isRecommend': instance.isRecommend,
                'marketPrice': instance.marketPrice,
                'material': instance.material,
                'name': instance.name,
                'packing': instance.packing,
                'price': instance.price,
                'saleCount': instance.saleCount,
                'stockCount': instance.stockCount,
                'updateTime': instance.update_time,
            })
        #"total":31,"size":10,"current":1,"orders":[],
        # "optimizeCountSql":true,"hitCount":false,
        # "countId":null,"maxLimit":null,"searchCount":true,"pages":4}
        # 传records 和total: 6, size: 10, current: 1
        return Response({'records': data,'countId':'null',
                         'current': 1,
                         'hitCount':'false',
                         'maxLimit': 'null','optimizeCountSql':'true',
                         'pages': total/10+1,
                         "orders": [],
                         'searchCount':'true',
                         'size': 10,'total':total,"code":200})




class GoodItemView(APIView):

    def get(self,request,goodsId):


        try:
            # 获取NewsChannel对象
            goodInfo = Shop.objects.filter( id = goodsId)


        except:
            return http.HttpResponseNotFound('未找到商品数据')

        data = []
        for instance in goodInfo:
            data.append({
                'applyUser': instance.applyUser,
                'category1Id': instance.category1Id_id,
                'category2Id': instance.category2Id_id,
                'createTime': instance.create_time,
                'detailList': instance.detailList.split(","),
                'floralLanguage': instance.floralLanguage,
                'id': instance.id,
                'imageUrl': instance.imageUrl.__str__(),
                'isDeleted': instance.isDeleted,
                'isRecommend': instance.isRecommend,
                'marketPrice': instance.marketPrice,
                'material': instance.material,
                'name': instance.name,
                'packing': instance.packing,
                'price': instance.price,
                'saleCount': instance.saleCount,
                'stockCount': instance.stockCount,
                'updateTime': instance.update_time,})

        # return Response({'goodsInfo': data[0],'allCount': "",'blessing': "",
        #                  'buyNow': 0,'count': 2,'token':'',
        #                  "code":200})

        # token = jwt.encode(b, 'sercet', algorithm='HS256')

        return Response({'goodsInfo': data[0],"code":200,'token':''})



class CategoryTreeView(APIView):

    def get(self,request):
        channels = ShopChannel.objects.all()

        data = []

        for channel in channels:
            children = []
            categorys = ShopCategory.objects.filter(channel = channel.id)
            for category in categorys:
                children.append({
                    'id': category.id,
                    'imageUrl': category.imageUrl.__str__(),
                    'name' : category.name
                })
            data.append({
                'children': children,
                'id': channel.id,
                'imageUrl': channel.imageUrl.__str__(),
                'name': channel.name
            })

        return Response({'data': data, "code": 200,'message': "成功"})




